package com.isc.homework02;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

/**
 * 1.编写一个接收端A和一个发送端B，使用UDP协议完成
 * 2.接收端在8888端口等待接收数据
 * 3.发送端想接收端发送数据 "四大名著是哪些?"
 * 4.接收端接收到发送端发送的问题后，返回"四大名著是<<红楼梦>>...",否则返回what?
 * 5.接收端和发送端程序退出
 */
public class SenderB {
    public static void main(String[] args) throws IOException {
        //使用UDP协议
        int port = 8889;
        DatagramSocket datagramSocket = new DatagramSocket(port);
        System.out.println("在"+port+"端口监听...");

        //向接收端发送信息
        System.out.println("请输入想要发送的消息:");
        Scanner scanner = new Scanner(System.in);
        String info = scanner.next();
        byte[] infoBytes = info.getBytes();
        //目的IP
        String destIp = "127.0.0.1";
        //目的端口
        int destPort = 8888;
        //使用UDP数据报发送信息
        DatagramPacket datagramPacket = new DatagramPacket(infoBytes, 0, infoBytes.length, InetAddress.getByName(destIp), destPort);
        //使用UDP套接字发送信息给接收端
        datagramSocket.send(datagramPacket);

        //接收 接收端回复的信息
        byte[] buf = new byte[1024];
        datagramPacket = new DatagramPacket(buf, buf.length);
        //接收到的数据放在datagramPacket中
        datagramSocket.receive(datagramPacket);
        byte[] data = datagramPacket.getData();
        int dataLength = datagramPacket.getLength();
        System.out.println("接收到的回复信息是:" + new String(data, 0, dataLength));

        //关闭资源
        datagramSocket.close();
        System.out.println("断开连接...");
    }
}
